<?php

namespace App\Service;

use App\Models\Cart;
use App\Models\Product;
use App\Models\ProductSku;
use App\Models\Scope\OnSaleScope;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class CartService
{
    public function get()
    {
        return Auth::user()->cart()->with(['productSku','product'])->whereHas('product', function ($query) {
            $query->withoutGlobalScope(OnSaleScope::class);
        })->get();
    }

    public function count()
    {
        if(Auth::user())
        {
            return \Auth::user()->cart()->count();
        }
        return 0;
    }

    public function add($skuId, $amount, $type, $product_id)
    {
        $user = Auth::user();
        // 从数据库中查询该商品是否已经在购物车中
        if ($item = $user->cart()->where('product_sku_id', $skuId)->first()) {

            if ($type == 1) {   // 增加
                // 如果存在则直接叠加商品数量
                $item->increment('amount', $amount);
            } else if($type == 2)  {  //减少
                if ($item->amount < $amount) {
                    $item->update(['amount' => 0]);
                } else {
                    $item->decrement('amount', $amount);
                }
            }
        } else {
            $product = Product::findOrFail($product_id);
            $productSku = ProductSku::findOrFail($skuId);
            // 否则创建一个新的购物车记录
            $item = new Cart([
                'amount' => $amount,
                'product_id' => $product_id,
                'product_title' => $product->title
            ]);
            $image = $productSku->image;
            $item->user()->associate($user);
            $item->product_sku_id = $productSku->id;
            $item->spec_sku_name = $productSku->spec_sku_name ?? '';
            $item->product_image = empty($image) ? $product->getOriginal('image') : Str::after($image,'com/');
            $item->save();
        }
        return $item;
    }

    /**
     * 删除购物车
     *
     * @param $skuIds
     * @return mixed
     */
    public function remove($skuIds)
    {
        // 可以传单个 ID，也可以传 ID 数组
        if (!is_array($skuIds)) {
            $skuIds = [$skuIds];
        }
        return Auth::user()->cart()->whereIn('id', $skuIds)->orWhere('product_sku_id', $skuIds)->delete();
    }
}
